package cn.kgc.vue.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.kgc.vue.common.ResponseResult;
import cn.kgc.vue.common.ResponseStatus;
import cn.kgc.vue.dto.DeptCount;
import cn.kgc.vue.dto.ObjectCount;
import cn.kgc.vue.dto.StudentInfor;
import cn.kgc.vue.entity.Course;
import cn.kgc.vue.form.StudentLsitForm;
import cn.kgc.vue.mapper.CourseMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.vue.entity.Student;
import cn.kgc.vue.service.StudentService;
import cn.kgc.vue.mapper.StudentMapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 * @description 针对表【student】的数据库操作Service实现
 * @createDate 2023-08-19 11:46:51
 */
@Service
@Transactional
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
        implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public ResponseResult getlist(StudentLsitForm studentLsitForm) {
        ResponseResult responseResult = new ResponseResult();
        Page<Student> page = new Page<>(studentLsitForm.getPage(), studentLsitForm.getLimit());
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(studentLsitForm.getName()), Student::getName, studentLsitForm.getName())
                .eq(StringUtils.isNotEmpty(studentLsitForm.getStudentNo()), Student::getStudentNo, studentLsitForm.getStudentNo())
                .eq(ObjectUtils.isNotNull(studentLsitForm.getCourseId()), Student::getCourseId, studentLsitForm.getCourseId()).orderByDesc(Student::getId);
        Page<Student> studentPage = studentMapper.selectPage(page, wrapper);
        List<Student> records = studentPage.getRecords();
        long total = studentPage.getTotal();
        //封装studnetInfor
        List<StudentInfor> list = records.stream().map(student -> {
            StudentInfor studentInfor = new StudentInfor();
            BeanUtils.copyProperties(student, studentInfor);
            Integer courseId = student.getCourseId();
            Course course = courseMapper.selectById(courseId);
            studentInfor.setCourseName(course.getCourseName());
            return studentInfor;
        }).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("student", list);
        responseResult.success(ResponseStatus.SUCCESS, map);
        return responseResult;
    }

    @Override
    public ResponseResult addorupdate(Student student) {
        ResponseResult responseResult = new ResponseResult();
        //判断student中是否携带id
        Integer id = student.getId();
        if (ObjectUtils.isNotNull(id)) {
            //修改操作
            studentMapper.updateById(student);
            responseResult.success(ResponseStatus.UPDATE_SUCCESS);
            return responseResult;
        }
        //不携带id则实现添加功能
        String studentNo = student.getStudentNo();
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getStudentNo, studentNo);
        Student student1 = studentMapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(student1)) {
            responseResult.fail(ResponseStatus.STUDENTNO_ACCOUNT);
            return responseResult;
        }
        studentMapper.insert(student);
        responseResult.success(ResponseStatus.ADD_SUCCESS);
        return responseResult;
    }

    @Override
    public ResponseResult batchAdd(MultipartFile file) throws Exception {
        ResponseResult responseResult = new ResponseResult();
        if (file.isEmpty()) {
            responseResult.fail();
            return responseResult;
        }
        InputStream inputStream = file.getInputStream();
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);
        List<Student> studentList = ExcelImportUtil.importExcel(inputStream, Student.class, importParams);
        for (Student student : studentList) {
            String studentNo = student.getStudentNo();
            LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Student::getStudentNo, studentNo);
            List<Student> studentList1 = studentMapper.selectList(wrapper);
            if (CollectionUtils.isNotEmpty(studentList1)) {
                throw new RuntimeException();
            }
            studentMapper.insert(student);
        }
        responseResult.success();
        return responseResult;
    }

    @Override
    public void excel(HttpServletResponse response, StudentLsitForm studentLsitForm) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(studentLsitForm.getName()), Student::getName, studentLsitForm.getName())
                .eq(StringUtils.isNotEmpty(studentLsitForm.getStudentNo()), Student::getStudentNo, studentLsitForm.getStudentNo())
                .eq(ObjectUtils.isNotNull(studentLsitForm.getCourseId()), Student::getCourseId, studentLsitForm.getCourseId());
        List<Student> studentList = studentMapper.selectList(wrapper);
        ExportParams exportParams = new ExportParams("学生信息表", "学生信息");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Student.class, studentList);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseResult objectCount() {
        ResponseResult responseResult = new ResponseResult();
        List<ObjectCount> list = studentMapper.objectCount();
        responseResult.success(ResponseStatus.SUCCESS, list);
        return responseResult;
    }

    @Override
    public ResponseResult deptCount() {
        //获取部门人数
        ResponseResult responseResult = new ResponseResult();
        List<DeptCount> list = studentMapper.deptCount();
        responseResult.success(ResponseStatus.SUCCESS,list);
        return responseResult;
    }
}




